﻿using MyCode.Project.Infrastructure.PayModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static MyCode.Project.Infrastructure.Constant.LxmConst;

namespace MyCode.Project.Infrastructure.Utils
{
    class HttpUtils
    {
        public void post(string url, Dictionary<string, string> map, StringBuilder result)
        {
            // 创建httppost.
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=GBK";
            Encoding encoding = Encoding.GetEncoding(FuiouPayConst.charset);

            StringBuilder buffer = new StringBuilder();
            int i = 0;
            foreach (KeyValuePair<string, string> kvp in map)
            {
                if (i > 0)
                {
                    buffer.AppendFormat("&{0}={1}", kvp.Key, FuYouPayUtils.UrlEncode(kvp.Value, Encoding.GetEncoding(FuiouPayConst.charset)));
                }
                else
                {
                    buffer.AppendFormat("{0}={1}", kvp.Key, FuYouPayUtils.UrlEncode(kvp.Value, Encoding.GetEncoding(FuiouPayConst.charset)));
                }
                i++;
            }

            byte[] postBody = encoding.GetBytes(buffer.ToString());
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postBody, 0, postBody.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(FuiouPayConst.charset));
                result.Append(reader.ReadToEnd());
            }
        }
    }
}
